import { PropType, defineComponent } from "vue";

export interface RateItemProps {
    icon?: any,
    index: number,
    allowHalf?: boolean,
    current: number,
}
export default defineComponent({
    name: "RateItem",
    props: {
        icon: {
            type: Object as PropType<RateItemProps['icon']>,
        },
        index: {
            type: Number  as PropType<RateItemProps['index']>,
        },
        allowHalf: {
            type: Boolean as PropType<RateItemProps['allowHalf']>,
        },
        current: {
            type: Number as PropType<RateItemProps['current']>,
        },
    },
    emits: ['mouseEnter', 'mouseEnterHalf', 'clickHalfStar', 'clickStar'],
    setup(props, { emit }) {
        const className = () => {
            let half = false;
            let full = false;
            if (props.index <= props.current - 1) {
                full = true;
            }
            if (props.index > props.current - 1 && props.index < props.current) {
                half = true;
            }
            return {
                'cm-rate-star': true,
                'cm-rate-star-zero': !full && !half,
                'cm-rate-star-half': props.allowHalf && half,
                'cm-rate-star-full': full
            }
        };

        const onMouseEnter = (index: number) => {
            emit('mouseEnter', index);
        }

        const onMouseEnterHalf = (index: number, e) => {
            emit('mouseEnterHalf', index, e);
        }

        const onClickStar = (index: number) => {
            emit('clickStar', index);
        }

        const onClickHalfStar = (index: number, e) => {
            emit('clickHalfStar', index, e);
        }

        return () => (
            <div class={className()}>
                <span onMouseenter={onMouseEnter.bind(null, props.index + 1)} 
                    onClick={onClickStar.bind(null, props.index + 1)}>
                    { props.icon }
                </span>
                {
                    props.allowHalf
                    ? <span class='cm-rate-star-content' onMouseenter={onMouseEnterHalf.bind(null, props.index + 0.5)}
                    onClick={onClickHalfStar.bind(null, props.index + 0.5)}>
                        { props.icon}
                    </span>
                    : null
                }
            </div>
        )
    }
})